//
//  AddOrderViewController.m
//  quickBatchManager
//
//  Created by jack on 15/9/24.
//  Copyright (c) 2015年 jack. All rights reserved.
//

#import "AddOrderViewController.h"
#import "AddOrderCell.h"
#import "NumberFieldModel.h"
#import "ProductModel.h"
#import "SizeModel.h"
#import "ColorModel.h"
@interface AddOrderViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@end

@implementation AddOrderViewController
{
    UIView *maintableView;
    UIButton *singelBtn;
    UIButton *mulBtn;
    NSMutableDictionary *selectNumber;
    NSMutableArray *colorList;
    NSMutableArray *sizeList;
    UILabel *totalLabel;
    UIButton *addBtn;
    UIButton *closeBtn;
    ProductModel *productInfo;
    NSArray *productList;
    
}
@synthesize backBtn,orderTable,colorSizeView,orderNumField,buyPriceField,totlePrices,isEdit;
- (void)viewDidLoad {
    [super viewDidLoad];
}


-(void)initData
{
  //  isEdit = NO;
    selectNumber=[[NSMutableDictionary alloc] init];
    colorList = [[NSMutableArray alloc] init];
    sizeList = [[NSMutableArray alloc] init];
    if(_modelNo!=nil)
    {
       // if(isEdit)
        //{
            productInfo = [AppService getProductByNo:_modelNo];
        [_imageView setImage:[UIImage imageNamed:[ToolUtils getImageLocalPath:productInfo.photo]]];
            [self ChooseProduct:productInfo];
       // }
    }
    
}

-(void)initUI
{
    
    [backBtn bk_whenTapped:^{
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    orderTable.dataSource = self;
    orderTable.delegate = self;
    orderTable.backgroundColor = [UIColor clearColor];
    
    
    singelBtn=[[UIButton alloc] initWithFrame:CGRectMake(marginSize, 10, 110, 40)];
    [singelBtn setTitle:@"单选" forState:UIControlStateNormal];
    
    [singelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [singelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [singelBtn setBackgroundImage:[ToolUtils imageWithColor:[UIColor colorWithRed:0.89 green:0.86 blue:0.84 alpha:1]] forState:UIControlStateNormal];
    [singelBtn setBackgroundImage:[ToolUtils imageWithColor:[UIColor colorWithRed:0.06 green:0.64 blue:0.78 alpha:1]] forState:UIControlStateSelected];
    [singelBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    
    
    
    
    mulBtn=[[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(singelBtn.frame), CGRectGetMinY(singelBtn.frame), CGRectGetWidth(singelBtn.frame), CGRectGetHeight(singelBtn.frame))];
    [mulBtn setTitle:@"多选" forState:UIControlStateNormal];
    
    [mulBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [mulBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    
    [mulBtn setBackgroundImage:[ToolUtils imageWithColor:[UIColor colorWithRed:0.89 green:0.86 blue:0.84 alpha:1]] forState:UIControlStateNormal];
    [mulBtn setBackgroundImage:[ToolUtils imageWithColor:[UIColor colorWithRed:0.06 green:0.64 blue:0.78 alpha:1]] forState:UIControlStateSelected];
    [mulBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
    
    
    [singelBtn bk_whenTapped:^{
        singelBtn.selected=YES;
        mulBtn.selected=NO;
        
        for (NSString *key in selectNumber) {
            NumberFieldModel *number=[selectNumber objectForKey:key];
            number.numberField.backgroundColor=[UIColor whiteColor];
            number.isSelect=NO;
        }
        
    }];
    
    [mulBtn bk_whenTapped:^{
        singelBtn.selected=NO;
        mulBtn.selected=YES;
    }];
    
    singelBtn.selected=YES;
    
    [colorSizeView addSubview:singelBtn];
    [colorSizeView addSubview:mulBtn];
    
    
    maintableView=[[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(singelBtn.frame), CGRectGetMaxY(singelBtn.frame)+5, 480, 100)];
    
    [colorSizeView addSubview:maintableView];
    maintableView.backgroundColor=[UIColor colorWithRed:0.73 green:0.72 blue:0.69 alpha:1];
    
    [self reloadNumber];
    
    /*** 添加关闭按钮***/
    addBtn = [[UIButton alloc] initWithFrame:CGRectMake(maintableView.frame.size.width/2 - 100, CGRectGetMaxY(maintableView.frame)+marginSize, 110, 40)];
    if(isEdit)
    {
        [addBtn setTitle:@"确定" forState:UIControlStateNormal];
    }else
    {
         [addBtn setTitle:@"添加" forState:UIControlStateNormal];
    }
   
    [addBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [addBtn setBackgroundImage:[UIImage imageNamed:@"btnred"] forState:UIControlStateNormal];
    
    closeBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(addBtn.frame)+marginSize, CGRectGetMaxY(maintableView.frame)+marginSize, 110, 40)];
    [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [closeBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [closeBtn setBackgroundImage:[UIImage imageNamed:@"btnred"] forState:UIControlStateNormal];
    
    [colorSizeView addSubview:addBtn];
    [colorSizeView addSubview:closeBtn];
    
    [colorSizeView setHidden:YES];
    
    
    [addBtn bk_whenTapped:^{
        if(!isEdit)
        {
            ProductModel *product=[AppService getProductByNo:orderNumField.text];
           
           
            
            [AppService putInSaleProduct:_saleOrder andProductId:product.productId andBuyPrice:buyPriceField.text andColorList:colorList andSizeList:sizeList andNumberList:selectNumber andSalePrices:buyPriceField.text];
            [self showToast:@"添加成功"];
            [self reloadUI];
        }else
        {
           
            [AppService updateSaleProductInfo:_saleOrder.saleOrderId andProductId:productInfo.productId andPductInfoId:_saleOrder.saleOrderInfoId andNumberList:selectNumber andColorList:colorList andSizeList:sizeList andSalePrices:[ToolUtils numberToStr:productInfo.salePrice]];
            [self reloadUI];
            [self showToast:@"更新成功"];
            
        }
      
    }];
    
    [closeBtn bk_whenTapped:^{
        if(_delegate!=nil && [_delegate respondsToSelector:@selector(didChange:andData:)])
        {
            [_delegate didChange:ChangeTypeOrder andData:nil];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    
    
    if(productInfo !=nil)
    {
        [self ChooseProduct:productInfo];
    }
    [self reloadUI];
}


-(void)reloadUI
{
    productList=[SaleOrderInfoModel searchWithWhere:@{@"saleOrderId":[ToolUtils numberToStr:_saleOrder.saleOrderId]} orderBy:nil groupBy:@"saleOrderInfoId" offset:0 count:0];
    if(productList && [productList count])
    {
        SaleOrderInfoModel *model = [productList objectAtIndex:0];
        double mtotalPrices=[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"productId":[NSString stringWithFormat:@"%ld",(long)model.productId],@"saleOrderInfoId":[ToolUtils numberToStr:model.saleOrderInfoId]}];
        
        totlePrices.text = [NSString stringWithFormat:@"总计：%0.0f 元",mtotalPrices*model.price];
    }

    [orderTable reloadData];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    
    
    if(productList!=nil && [productList count]>0)
        return [productList count];
    else
        return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *reuseIdetify = @"AddOrderCell";
    AddOrderCell  *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdetify];
    if(!cell){
        
        
        NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"AddOrderCell" owner:self options:nil];
        for(id oneObject in nib){
            if([oneObject isKindOfClass:[AddOrderCell class]]){
                cell = (AddOrderCell *) oneObject;
            }
        }
        
    }
    cell.backgroundColor = [UIColor clearColor];
    
    SaleOrderInfoModel *model = [productList objectAtIndex:indexPath.row];
    cell.titleNameLabel.text = [NSString stringWithFormat:@"%@",model.product.modelNo];
//    cell.numberLabel.text = [NSString stringWithFormat:@"%0.0f",[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"productId":[NSString stringWithFormat:@"%d",model.productId],@"saleOrderId":[ToolUtils numberToStr:model.saleOrderId]}]];
    double total=[SaleOrderInfoModel sumWithWhere:@"productNumber" where:@{@"productId":[NSString stringWithFormat:@"%ld",(long)model.productId],@"saleOrderInfoId":[ToolUtils numberToStr:model.saleOrderInfoId]}];
    cell.numberLabel.text = [NSString stringWithFormat:@"%0.0f",total];
    return cell;
    
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if([textField isEqual:orderNumField] && !isEdit)
    {
        ChooseOrderVC *menuVc=[[ChooseOrderVC alloc]init];
        UIPopoverController *popover=[[UIPopoverController alloc]initWithContentViewController:menuVc];
        popover.popoverContentSize=CGSizeMake(200, 300);
        menuVc.delegate = self;
        [popover presentPopoverFromRect:CGRectMake(100, 0, 10, 10) inView:orderNumField permittedArrowDirections:UIPopoverArrowDirectionUnknown animated:YES];
      //  return NO;
    }
}
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
//{
//    if([textField isEqual:orderNumField] && !isEdit)
//    {
//        ChooseOrderVC *menuVc=[[ChooseOrderVC alloc]init];
//        UIPopoverController *popover=[[UIPopoverController alloc]initWithContentViewController:menuVc];
//        popover.popoverContentSize=CGSizeMake(200, 300);
//        menuVc.delegate = self;
//        [popover presentPopoverFromRect:CGRectMake(100, 0, 10, 10) inView:orderNumField permittedArrowDirections:UIPopoverArrowDirectionUnknown animated:YES];
//        return NO;
//    }
//    return YES;
//}

-(void)textFieldChanged:(id)sender
{
    UITextField *text=(UITextField*)sender;
    double total=0;
    for (NSString *key in selectNumber) {
        NumberFieldModel *number=[selectNumber objectForKey:key];
        if(number.isSelect && mulBtn.isSelected)
        {
            number.numberField.text=text.text;
        }
        
        total+=[number.numberField.text intValue];
    }
    
    totalLabel.text=[NSString stringWithFormat:@"    共计：%.0f件",total];
    
}


-(void) reloadNumber
{
    
    for (UIView *view in maintableView.subviews) {
        [view removeFromSuperview];
    }
    
    if(sizeList.count>0 && colorList.count>0)
    {
        colorSizeView.hidden=NO;
        
        productInfo=[AppService getProductByNo:orderNumField.text];
        NSDictionary *sizeColor=[AppService getSizeAndColorByModel:orderNumField.text];
        colorList=[sizeColor objectForKey:@"color"];
        sizeList=[sizeColor objectForKey:@"size"];
        
        int width=580/(sizeList.count+1);
        int height=40;
        
        
        for (int i=0; i<=colorList.count; i++) {
            
            for (int j=0; j<=sizeList.count; j++) {
                if(i>0 && j>0)
                {
                    ProductInfoModel *sizemodel = [ProductInfoModel searchSingleWithWhere:@{@"productId":[ToolUtils numberToStr:productInfo.productId],@"sizeName":sizeList[j-1],@"colorName":colorList[i-1]} orderBy:nil];
                    
                    SaleOrderInfoModel *salemodel;
                    if(isEdit)
                    {
                        salemodel = [SaleOrderInfoModel searchSingleWithWhere:@{@"productId":[NSString stringWithFormat:@"%ld",(long)productInfo.productId],@"sizeName":sizeList[j-1],@"colorName":colorList[i-1],@"saleOrderId":[ToolUtils numberToStr:_saleOrder.saleOrderId],@"saleOrderInfoId":[NSString stringWithFormat:@"%ld",(long)_saleOrder.saleOrderInfoId]} orderBy:nil];
                    }
                
                 //   NSLog(@"salemodel:num :%d %@",salemodel.productNumber,_saleOrder.saleOrderId);
                    
                    NSString *key=[NSString stringWithFormat:@"%d_%d",i,j];
    
                    
                    NumberFieldModel *number=[selectNumber objectForKey:key];
                    
                    UITextField *numberField=[[UITextField alloc] initWithFrame:CGRectMake((width+1)*j+1,(height+1)*i+1, width, height)];
                    numberField.backgroundColor=[UIColor whiteColor];
                    numberField.textAlignment=NSTextAlignmentCenter;
                    numberField.delegate=self;
                    if(isEdit)
                    {
                        numberField.text = [NSString stringWithFormat:@"%d",salemodel.productNumber];
                    }
                    numberField.font=[UIFont systemFontOfSize:16];
                    numberField.textColor=[UIColor colorWithRed:0.50 green:0.49 blue:0.46 alpha:1];
                    numberField.keyboardType=UIKeyboardTypeNumberPad;
                    number.numberField=numberField;
                    [self addTextFieldChange:numberField];
                    
                    
                    UIView *view=[[UIView alloc] initWithFrame:numberField.frame];
                    
                    view.userInteractionEnabled=YES;
                    
                    [view bk_whenTapped:^{
                        
                        if(mulBtn.selected)
                        {
                            number.isSelect=!number.isSelect;
                            if(!number.isSelect)
                            {
                                numberField.backgroundColor=[UIColor whiteColor];
                                [numberField resignFirstResponder];
                            }
                            else {
                                numberField.backgroundColor=[UIColor colorWithWhite:0.95 alpha:1];
                                [numberField becomeFirstResponder];
                            }
                            
                        }
                        else
                        {
                            [numberField becomeFirstResponder];
                        }
                        
                    }];
                    
                    UILabel *tagView = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 27, 13)];
                    [tagView setBackgroundColor:COLOR(254, 220, 178, 1)];
                    [tagView setFont:[UIFont systemFontOfSize:10]];
                    [tagView setTextAlignment:NSTextAlignmentCenter];
                    [tagView setTextColor:[UIColor colorWithRed:0.50 green:0.49 blue:0.46 alpha:1]];
                    tagView.layer.cornerRadius = 5.0;
                    tagView.layer.masksToBounds = YES;
                    tagView.layer.borderWidth = 0.5;
                    tagView.text = [NSString stringWithFormat:@"%d",sizemodel.productNumber];
                    tagView.layer.borderColor = [COLOR(254, 190, 119, 1) CGColor];
                    [view addSubview:tagView];
                    
                    [maintableView addSubview:numberField];
                    [maintableView addSubview:view];
                }
                else
                {
                    
                    UILabel *title=[[UILabel alloc] initWithFrame:CGRectMake((width+1)*j+1,(height+1)*i+1, width, height)];
                    if(i==0)
                        title.backgroundColor=[UIColor colorWithRed:0.97 green:0.96 blue:0.93 alpha:1];
                    else title.backgroundColor=[UIColor whiteColor];
                    
                    title.textAlignment=NSTextAlignmentCenter;
                    title.font=[UIFont systemFontOfSize:16];
                    title.textColor=[UIColor colorWithRed:0.50 green:0.49 blue:0.46 alpha:1];
                    
                    
                    if(i==0 && j==0)
                        title.text=@"颜色";
                    else if(j==0)
                    {
                        title.text=colorList[i-1];
                    }
                    else if(i==0)
                    {
                        title.text=sizeList[j-1];
                    }
                    
                    [maintableView addSubview:title];
                }
                
                
            }
            
            
        }
        
        maintableView.frame=CGRectMake(maintableView.frame.origin.x,maintableView.frame.origin.y, (width+1)*(sizeList.count+1)+1, (height+1)*(colorList.count+2)+1);
        
        totalLabel=[[UILabel alloc] initWithFrame:CGRectMake(1,CGRectGetHeight(maintableView.frame)-1-height, CGRectGetWidth(maintableView.frame)-2, height)];
        totalLabel.backgroundColor=[UIColor whiteColor];
        
        totalLabel.textAlignment=NSTextAlignmentLeft;
        totalLabel.font=[UIFont systemFontOfSize:16];
        totalLabel.textColor=[UIColor colorWithRed:0.50 green:0.49 blue:0.46 alpha:1];
        totalLabel.text=[NSString stringWithFormat:@"    共计：%d件",0];
        
        [maintableView addSubview:totalLabel];
        
        for (NSLayoutConstraint *ct in  [colorSizeView constraints]) {
            if(ct.firstAttribute==NSLayoutAttributeHeight)
            {
                ct.constant=CGRectGetMaxY(maintableView.frame)+10;
            }
        }
        
        [addBtn setFrame:CGRectMake(maintableView.frame.size.width/2 - 100, CGRectGetMaxY(maintableView.frame)+marginSize, 110, 40)];
        [closeBtn setFrame:CGRectMake(CGRectGetMaxX(addBtn.frame)+marginSize, CGRectGetMaxY(maintableView.frame)+marginSize, 110, 40)];
        
        
    }
}


-(void)ChooseProduct:(ProductModel *)product
{
    [colorList removeAllObjects];
    [sizeList removeAllObjects];
    [selectNumber removeAllObjects];
    orderNumField.text = product.modelNo;
    orderNumField.tag = 100;
    if(![orderNumField.text isBlank])
    {
        buyPriceField.text = [NSString stringWithFormat:@"%0.0f",product.salePrice];
        
        NSDictionary *sizeColor=[AppService getSizeAndColorByModel:product.modelNo];
        colorList=[sizeColor objectForKey:@"color"];
        sizeList=[sizeColor objectForKey:@"size"];
        
        
        if(sizeList.count>0 && colorList.count>0)
        {
            for (int i=1; i<=colorList.count; i++) {
                for (int j=1; j<=sizeList.count; j++) {
                    
                    NumberFieldModel *number=[[NumberFieldModel alloc] init];
                    number.isSelect=NO;
                    number.number=0;
                    [selectNumber setObject:number forKey:[NSString stringWithFormat:@"%d_%d",i,j]];
                }
            }
            
            [self reloadNumber];
            colorSizeView.hidden = NO;
        }
        
        
    }
}

@end
